package com.starzy.mr;

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @Author: starzy https://www.cnblogs.com/starzy
 * @Description:
 * @Date: Created in 10:27 2020/12/15
 */
public class WordAndLineCounterMR {
    /**
     * mapreduce全局计数器是用枚举类进行计数器定义
     * COUNT_WORDS 用来统计总单词数
     *COUNT_LINES 用来统计总行数
     */
    enum MyCounterWorldCount{
        COUNT_WORDS,COUNT_LINES
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //指定HDFS参数
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        //设置Jar包路径
        job.setJarByClass(WordAndLineCounterMR.class);
        job.setMapperClass(WordAndLineCounterMapper.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // 本地路径
        Path inputPath = new Path("D:/data/words/input");
        FileInputFormat.setInputPaths(job, inputPath);

        Path outputPath = new Path("D:/data/words/output");
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }
        FileOutputFormat.setOutputPath(job, outputPath);

        // 最后提交任务
        boolean waitForCompletion = job.waitForCompletion(true);
        System.exit(waitForCompletion ? 0 : 1);
    }

    private static class WordAndLineCounterMapper extends Mapper<LongWritable, Text,Text,LongWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //获取计数器
            Counter counter = context.getCounter(MyCounterWorldCount.COUNT_LINES);
            //计数器计数
            counter.increment(1L);
            String[] words = value.toString().split(" ");
            for (String word : words) {
                if (StringUtils.isNotBlank(word)){
                    context.getCounter(MyCounterWorldCount.COUNT_WORDS).increment(1L);
                }
            }
        }
    }
}
